﻿using MediatR;
using PoemGame.Domain.GameAggregate.Events;
using PoemGame.Domain.Seedwork;
using PoemGame.Events.Shared;

namespace PoemGame.Events.MediatR
{
    /// <summary>
    /// 使用MediatR发布内部事件
    /// </summary>
    public class LocalEventBus : ILocalEventBus
    {
        private readonly IMediator _mediator;

        public LocalEventBus(IMediator mediator)
        {
            _mediator = mediator;
        }

        public async Task PublishAsync(BaseEventDataLocal data)
        {
            if (data is GameFinishEventDataLocal finishData)
            {
                await PublishAsync<GameFinishEventDataLocal>(finishData);
            }
            else if (data is GamePlayEventDataLocal playData)
            {
                await PublishAsync<GamePlayEventDataLocal>(playData);
            }
            else if (data is PlayerJoinGameEventDataLocal joinData)
            {
                await PublishAsync<PlayerJoinGameEventDataLocal>(joinData);
            }
            else if (data is PlayerLeaveGameEventDataLocal leaveData)
            {
                await PublishAsync<PlayerLeaveGameEventDataLocal>(leaveData);
            }
        }

        private async Task PublishAsync<T>(T data) where T : BaseEventDataLocal
        {
            var eventdata = new LocalEvent<T>(data);
            await _mediator.Publish(eventdata);
        }
    }

}
